package com.ai.config.security.handler;

import com.ai.common.CommonResponse;
import com.ai.common.constant.enumP.ResultCode;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;
import springfox.documentation.spring.web.json.Json;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @Author: Hutengfei
 * @Description: 权限拒绝处理逻辑（无权限）
 * @Date Create in 2019/9/3 20:56
 */
@Component
@Slf4j
public class CustomizeAccessDeniedHandler implements AccessDeniedHandler {

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException e) throws IOException, ServletException {

        log.info("============================================ 无权限进行操作  ==================================================");

        // 执行时间
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date d= new Date();
        String time = sdf.format(d);
        log.info("Time           : " + time);
        // 打印请求 URL
        log.info("URL :            " + request.getRequestURL());
        // 打印 请求方法
        log.info("HTTP Method:     " + request.getMethod());
        // 打印请求的 IP
        log.info("IP             : " + request.getRemoteHost());

        log.info("=======================================================================================================");


        response.setContentType("application/json;charset=UTF-8");
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);

        ServletOutputStream outputStream = response.getOutputStream();

        CommonResponse result = CommonResponse.result(ResultCode.NO_PERMISSION);

        outputStream.write(JSON.toJSONString(result).getBytes("UTF-8"));

        outputStream.flush();
        outputStream.close();

    }
}
